$(document).ready(function () {
	fetchOneBookData();

    // $("#BID").val(BID);
	$("#add-comment-btn").click(function() {
		if (commentValidate()) {
			var rate = $("#book-rate").val();
			$.ajax({
		        type: "POST",
		        data: {BID: $("#BID").val(), EvalContent: $("#book-comment-text").val(), EvalGrade: rate?rate:0},
		        url: "../Handle/EvaluateHandlerService.ashx?method=Add_New_Evaluate",
		        dataType: "json",
		        success: function (data) {
		            //console.log(data);
		            $('#book-rate').rating('clear');
		            $("#book-comment-text").val("");
		            $("#dialog-modal-label").text("书评提交成功！");
                	$("#DialogModal").modal("show");
		        }
		    });
		}
	});

	$('#book-rate').rating({
        step: 1,
        size: 'xs',
        min: 0,
        max: 5,
        showClear: false,
        language:'zh',
        //starCaptions: { 1: '一般', 2: '还不错', 3: '值得推荐', 4: '力荐', 5: '经典' },
        starCaptionClasses: { 1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success' }
    });

    $("#comment-list-panel").click(function(e) {
	    $.ajax({
	        type: "GET",
	        data: {BID: $("#BID").val(), PageIndex: 1, PageSize: 20},
	        url: "../Handle/EvaluateHandlerService.ashx?method=Get_One_Book_Evaluate_From_BID",
	        dataType: "json",
	        success: function (data) {
	        	//console.log(data);
	        	if(0 == data.rows.length) {
	        		$("#book-comment-list").text("本书暂无评论");
	        	} else {
                    $("#book-comment-count").text(data.RecordCount+"次");
	        		var outputHtml = getCommentListOutputHtml(data.rows);
	        		$("#book-comment-list").html(outputHtml);
	        	}
	        }
	    });
    });

    $(document)
        .on('click', '.thumbnail-img', function(e) {
            e.preventDefault();
            //alert($(this).attr("value"));
            window.open("Book.aspx?BID="+$(this).attr("value"));      
        })
});

function fetchOneBookData() {
	var params = GetRequest();
	var BID = "";
	for(var i in params) {//不使用过滤
        BID = params[i];
        break;
    }
	if ("" == BID) {return;}
	$("#BID").val(BID);
    $.ajax({
        type: "GET",
        data: {BID: BID},
        url: "../Handle/BookHandlerService.ashx?method=Get_One_Book_Info_From_BID",
        dataType: "json",
        success: function (data) {
            //console.log(data.rows[0]);
        	data = data.rows[0];
            $("#book-id").text(data["BID"]);
        	$("#book-name").text(data["Bname"]);
        	$("#book-img").attr('src',data["Pname"]);
        	$("#book-author").text(data["Author"]);
        	$("#book-press").text(data["Press"]);
        	$("#book-pym").text(data["PYM"]);
        	$("#book-price").text(data["Price"] + "元");
        	$("#book-isbn").text(data["ISBN"]);
        	$("#book-cid").text(data["cname"]);
            $("#book-desc").text(data["Descript"]);
            $("#book-borrowed-num-count").text(data["Bnum"] + "次");
            $("#book-borrowed-day-count").text((data["DayNumSUM"]?data["DayNumSUM"]:0) + "天");
        	$("#book-rate-star-count").text((data["EgradeNumSUM"]?data["EgradeNumSUM"]:0) + "颗");
            $("#book-comment-count").text((data["EvaluateNumSUM"]?data["EvaluateNumSUM"]:0) + "次");
            $("#book-owner").text(data["rxnf"]+data["cid"]+"班 "+data["sname"]);

            if ("1" == data["Flag"]) {
                $("#book-status").text("已下架");
            } else {
                switch(data["Cstatus"]) {
                    case "0":
                        $("#book-status").text("正常可借阅");
                    break;
                    default:
                        $("#book-status").text("在借");
                    break;
                }
            }
            
            fetchSameCategoryBookList(data["cname"].split(",")[0]);
        }
    });
}

function commentValidate() {
    return $("#add-comment-form").validate({
        errorClass: "warning",
        rules: {
            bookCommentText: {
                required: true,
                minlength: 10,
                maxlength: 500,
            },
        },
        messages: {
            bookCommentText: {
                required: "评论内容不能为空",
                minlength: "评论内容应不少于10个字",
                maxlength: "评论内容应不多于500个字",
            },
        }
    }).form();
}

function GetRequest() {  
   var url = location.search; //获取url中"?"符后的字串  
   var theRequest = new Object();  
   if (url.indexOf("?") != -1) {  
      var str = url.substr(1);  
      strs = str.split("&");  
      for(var i = 0; i < strs.length; i ++) {  
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
      }  
   }  
   return theRequest;  
}

function getCommentListOutputHtml(items) {
	var outputHtml = "";
	for (var i = 0; i < items.length; i++) {
        var item = items[i];
        
        outputHtml += "<div class='panel panel-warning'><div class='panel-heading'>"+
                       "<div class='row'><div class='col-md-4 col-xs-4'>"+item["GradeName"]+item["ClassName"]+"班 "+item["StudentName"]+"</div>"+
        				"<div class='col-md-4 col-xs-4 text-center'>" +item["egrade"] +"颗星</div>"+
                        "<div class='col-md-4 col-xs-4 text-right'>"+"<span>"+item["bdate"]+"</span></div></div></div>"+
                        "<div class='panel-body'>"+item["econtent"]+"</div></div>";
    }
    return outputHtml;
}

function fetchSameCategoryBookList(cname) {
    $.ajax({
        type: "GET",
        data: {CategoryName: cname, PageIndex: 1, PageSize: 6},
        url: "../Handle/BookHandlerService.ashx?method=Search_Book_List_From_CategoryID",
        dataType: "json",
        success: function (data) {
            //console.log(data);
            if(data.rows.length == 0) {
                $('#category-book-list').html("<p>非常抱歉！该分类下暂无书</p>");
                return;
            }
            
            $('#same-category-list').html(getBookListOutputHtml(data.rows));
            
            // $(function () {
            //     $('[data-toggle="popover"]').popover({
            //         trigger: 'hover focus',
            //         container: 'body',
            //         placement: 'auto right',
            //         html: 'true'
            //     });
            // });
        }
    });
}

function getBookListOutputHtml(items) {
    var outputHtml = "";
    if (items.length > 0) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            //var dataContent = "<p><small>" + item["Author"] + " / " + item["PYM"] + " / " + item["Press"] + "</small></p><small>" + subStrToLimitLength(item["Descript"], 150) + "</small>";
            var btnContent = "<p style='margin-bottom:0px;'><small>正常</small></p>";
            if ("1" == item["Cstatus"] || "2" == item["Cstatus"]) {
                btnContent = "<p style='margin-bottom:0px;'><small>已借出</small></p>"
            } else if ("1" == item["Flag"]) {
                btnContent = "<p style='margin-bottom:0px;'><small>已下架</small></p>"
            }
            
            outputHtml += "<div class='col-md-6 col-xs-6'>" +
            "<div class='thumbnail' style='border: 0 none;'>" +
                "<img src='" + item["Pname"] +
                "' style='width: 126px;height: 168px;' alt='图书封面' title='" + item["Bname"] +"' class='thumbnail-img' value='"+item["BID"]+"'>" +
                "<div class='caption'>" +
                "<p>" + subStrToLimitLength(item["Bname"], 5) + "</p>" +
                "<p><small>" + subStrToLimitLength(item["Author"], 8) + "</small></p>" +
                btnContent+
                "</div>" +
            "</div>" +
            "</div>";
        }
    }
    return outputHtml;
    // return outputHtml;
}